package net.lzzy.practices.web;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstants;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.AuthUtils;
import net.lzzy.practices.utils.FileUtils;
import net.lzzy.practices.utils.StringUtils;
import net.lzzy.practices.web.models.ApiResult;
import net.lzzy.practices.web.models.LoginInfo;
import net.lzzy.practices.web.models.RegisterInfo;
import net.lzzy.practices.web.models.VmUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author zly on 2022/5/12
 * Description:
 * @PathVariable请求路径中占位符的值
 * @RequestParam用来处理Content-Type 为 application/x-www-form-urlencoded编码的内容，将请求参数名映射到方法参数名
 * @GetMapping是一个组合注解，等价于@RequestMapping(method = RequestMethod.GET)，它将HTTP Get请求映射到特定的处理方法上
 *
 */
@Api(tags = "用户认证")
@CrossOrigin
@RestController
@RequestMapping(ApiConstants.ROUTE_AUTH_ROOT)

public class AuthApiController {

    private final UserService service;


    public AuthApiController(UserService service) {
        this.service = service;
    }
    @ApiOperation(value = "用户登录",notes = "<b>参数包括</b><br/>；&nbsp;&nbsp;&nbsp;用户名和密码")
    @ApiImplicitParam(name="json",value = "登录信息",dataType = "LoginInfo",dataTypeClass = LoginInfo.class,paramType = "body",required = true)
    @PostMapping(value = ApiConstants.ROUTE_AUTH_LOGIN, produces = ApiConstants.API_PRODUCES_JSON)
    public ApiResult login(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String password = json.getString("password");
        String salt = service.getSalt(username);
        User user = service.check(username, StringUtils.md5Encode(password, salt));
        if (user == null) {
            return new ApiResult(false, Messages.WRONG_PASSWORD.toString(), null);
        }
        if (user.getType() < 0) {
            return new ApiResult(false, Messages.USER_FORBIDDEN.toString(), null);
        }
       VmUser vmUser = VmUser.apiLogin(user);
        return new ApiResult(true, Messages.SUCCESS.toString(), vmUser);
    }
    @ApiOperation(value = "用户注销",notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;token值")
    @PostMapping(ApiConstants.ROUTE_AUTH_LOGOUT)
    public ApiResult logout(@RequestParam String token) {
        return new ApiResult(true, AuthUtils.logout(token), null);

    }

    @ApiOperation(value = "用户是否存在",notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;用户名")
    @GetMapping(ApiConstants.ROUTE_AUTH_EXISTS)
    public ApiResult isUserExists(@PathVariable String user) {
        boolean exists = service.isUserNameOccpuied(user);
        return new ApiResult(true, exists ? "用户名已被使用" : "", exists);
    }

    @ApiOperation(value = "用户注册",notes = "<b>参数包括：" +"</b><br/>1.nick(String)<br/>2.user(String)<br/>3.phone(String)<br/>"+
            "4.avatar(String)<br/>5.email(String)<br/>6.password(String)<br/>7.apply(boolean)<br/>"
    )
    @PostMapping(ApiConstants.ROUTE_AUTH_REGISTER)
    public ApiResult register(@RequestBody RegisterInfo info) {
        String nick=info.getNick();
        String user=info.getUser();
        String phone=info.getPhone();
        String avatar=info.getAvatar();
        String email=info.getEmail();
        String password=info.getPassword();
        boolean apply=info.isApply();
        String salt= UUID.randomUUID().toString();
        if(StringUtils.isEmpty(nick)||StringUtils.isEmpty(password)||StringUtils.isEmpty(phone)||StringUtils.isEmpty(user)||StringUtils.isEmpty(avatar)){
            return new ApiResult(false,Messages.INCOMPLETE_INFO.toString(),null);
        }
        if(service.isUserNameOccpuied(user)){
            return new ApiResult(false,"用户名已经被注册使用",user);
        }
        User usr = new User();
        usr.setApplyTeacher(apply);
        usr.setType(User.TYPE_STUDENT);
        usr.setAvatar(avatar);
        usr.setEmail(email);
        usr.setPhone(phone);
        usr.setNickName(nick);
        usr.setPassword(StringUtils.md5Encode(password, salt));
        usr.setSalt(salt);
        usr.setUserName(user);
        VmUser vmUser = VmUser.apiLogin(service.register(usr));
        return new ApiResult(true, "注册成功", vmUser);
    }


    @Value("${user.pic}")
    private  String imgPath;

    @ApiOperation(value = "上传文件",notes = "<b>参数包括：</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;文件名String")
    @PostMapping(ApiConstants.ROUTE_AUTH_UPLOAD)
    public ApiResult upload(MultipartFile file){
        JSONObject result = FileUtils.upload(file,imgPath);
        return new ApiResult(result.getBoolean("status"),
                result.getString("message"),
                result.getString("url"));
    }
}
